package main

import (
	"log"
	"strings"
	"strconv"
	"net/http"
	"html/template"
)

type AnimaRes struct {
	Name string
	Title string
	Info AnimaInfo
	OthSeasons []string
	Characters []string
}

func handleAnima(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	if r.Method != http.MethodGet && r.Method != http.MethodPost &&
		r.PostForm.Get("method") != "delete" {
		t, _ := template.ParseFiles("template/rawtext.gtpl")
		t.Execute(w, "Invalid http method.")
		return
	}

	var (
		res AnimaRes
		pathSplits []string = make([]string, 3, 3)
	)
	urlPath := r.URL.Path
	pathSplits = strings.SplitN(urlPath, "/", 3)
	res.Name = pathSplits[2]

	qs := dborm.QueryTable("anima_info")
	err := qs.Filter("name", res.Name).One(&res.Info)
	if err != nil {
		log.Println("DEBUG:", err)
		http.NotFound(w, r)
		return
	}

	if r.Method == http.MethodGet {
		// Fill something for pages.
		res.Title = res.Name
		res.OthSeasons = stringToSlice(res.Info.OthSeasons)
		res.Characters = stringToSlice(res.Info.Characters)

		t, _ := template.ParseFiles("template/anima.gtpl")
		t.Execute(w, res)
		return
	} else if r.Method == http.MethodPost {
		if r.Form.Get("name") != res.Name {
			t, _ := template.ParseFiles("template/rawtext.gtpl")
			t.Execute(w, "bad form.")
			return
		}

		_, err_d := dborm.Delete(&res.Info)
		if err_d == nil {
			t, _ := template.ParseFiles("template/delete-success.gtpl")
			t.Execute(w, res)
			return
		} else {
			t, _ := template.ParseFiles("template/rawtext.gtpl")
			t.Execute(w, "Database error: Delete error.")
			return
		}
	}
	return
}

func handleAnimaEdit(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	var (
		res AnimaRes
		pathSplits []string = make([]string, 3, 3)
	)

	if r.Method == http.MethodGet {
		urlPath := r.URL.Path
		pathSplits = strings.SplitN(urlPath, "/", 3)
		res.Name = pathSplits[2]
		res.Title = "EDIT: " + res.Name

		qs := dborm.QueryTable("anima_info")
		err := qs.Filter("name", res.Name).One(&res.Info)
		if err != nil {
			if r.Form.Get("new") == "true" {
				res.Info.Name = res.Name
				res.Info.Series = res.Info.Name
				res.Info.Category = "anima"
				res.Info.TextRole = "角色 | 声优 | 简介\n:---- | :---- | :----\n"
				_, err_i := dborm.Insert(&res.Info)
				if err_i != nil {
					t, _ := template.ParseFiles("template/rawtext.gtpl")
					t.Execute(w, "Database error: Update error.")
					return
				}
			} else {
				log.Println("DEBUG:", err)
				http.NotFound(w, r)
				return
			}
		}

		t, err := template.ParseFiles("template/anima-edit.gtpl")
		if err != nil {
			log.Println("DEBUG: ParseFiles:", err)
		}
		t.Execute(w, res)
		return
	} else if r.Method == http.MethodPost {
		var (
			err_i error
		)
		res.Info.Id, err_i = strconv.Atoi(r.PostForm.Get("id"))
		err := dborm.Read(&res.Info)
		if err != nil || err_i != nil ||
			res.Info.Name != r.PostForm.Get("name") {
			t, _ := template.ParseFiles("template/rawtext.gtpl")
			t.Execute(w, "Database error: ID error.")
			return
		}

		// Fill values
		res.Info.JpName = r.PostForm.Get("jp_name")
		res.Info.OthName = r.PostForm.Get("oth_name")
		res.Info.Series = r.PostForm.Get("series")
		res.Info.Category = "anima"
		res.Info.Auther = r.PostForm.Get("auther")
		res.Info.Director = r.PostForm.Get("director")
		res.Info.Product = r.PostForm.Get("product")
		res.Info.ShowTime = r.PostForm.Get("show_time")
		res.Info.OthSeasons = r.PostForm.Get("oth_seasons")
		res.Info.OrigClass = r.PostForm.Get("orig_class")
		res.Info.Characters = r.PostForm.Get("characters")
		res.Info.TextNote = r.PostForm.Get("text_note")
		res.Info.TextRole = r.PostForm.Get("text_role")
		res.Info.Synopsis = r.PostForm.Get("synopsis")
		res.Info.RelatedLinks = r.PostForm.Get("related_links")

		_, err_i = dborm.Update(&res.Info)
		if err_i != nil {
			t, _ := template.ParseFiles("template/rawtext.gtpl")
			t.Execute(w, "Database error: Update error.")
			return
		}

		//res.Title = "UPDATE SUCCESS: " + res.Info.Name
		t, _ := template.ParseFiles("template/update-success.gtpl")
		t.Execute(w, res)
		return
	} else {
		t, _ := template.ParseFiles("template/rawtext.gtpl")
		t.Execute(w, "Invalid http method.")
		return
	}
	return
}

